package com.axungu.web.freemarker;


import freemarker.template.Configuration;
import freemarker.template.TemplateModelException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.PostConstruct;
import java.util.Map;


/**
 * Freemarker 配置扩展，主要是针对自己定义方法的扩展
 *
 * @author jtoms.shen
 * @version 1.0
 * @date 2018/12/6 15:55
 */
@Slf4j
@Component
public class FreeMarkerConfigurerExtend implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @PostConstruct
    public void setSharedVariable() throws TemplateModelException {
        Map<String, Object> map = applicationContext.getBeansWithAnnotation(FreemarkerComponent.class);

        Configuration configuration = this.freeMarkerConfigurer.getConfiguration();

        for (String key : map.keySet()) {
            configuration.setSharedVariable(key, map.get(key));
        }

        this.freeMarkerConfigurer.setConfiguration(configuration);
    }

}